import datetime
import json
import random
import requests
from noteserver import models
from django.shortcuts import render,HttpResponse
from django.db.models import Q

""" 
微信登录需要的一些参数
 """
OPENIDURL = r"https://api.weixin.qq.com/sns/jscode2session"
APPID = r"wxac9f9ceaf2de44b1"      # 小程序ID
SECRET = r"d76f8f29324221160e60799e01af27a3" 

def index(request):
    return HttpResponse("无任何请求")

""" 
功能：
    获得微信登录需要的openid, 如果该微信用户还没注册，就自动注册用户
参数：
    request包含几个POST字段：jscode,获取openid必备的
返回：
    返回用户的userID
 """
def queryOpenidAndCreateUser(request):
    print("query Openid And Create User")
    # url一定要拼接，不可用传参方式
    if "jscode" in request.GET:
        jscode = request.GET.get('jscode')
    else:
        return HttpResponse("没有获得openID")
    # headurl = request.GET.get('headurl')
    url = OPENIDURL + "?appid=" + APPID + \
        "&secret=" + SECRET + "&js_code=" + jscode + "&grant_type=authorization_code"
    r = requests.get(url)
    openid = r.json()['openid']
    if not openid:
        return HttpResponse("没有获得openID")

    #查找用户表中是否有这个openID
    open_id = models.Users.objects.filter(openID=openid)
    # 如果没有，随机生成6位数的用户号，初始密码为123456，存到Users表中
    if not open_id:
        user = models.Users()
        has_uid = 1
        while has_uid:
            uID = random.randint(10000, 99999)
            has_uid = models.Users.objects.filter(userID=uID)
        user.userID = str(uID)
        user.openID = openid
        user.password = str(123456)
        user.nickName = str("无名"+user.userID)
        user.save()
    else:
        user = models.Users.objects.filter(openID=openid)[0]
    # 返回userID
    return HttpResponse(user.userID)

""" 
功能：
    修改用户昵称
参数：request包含几个POST字段
    userID: 登录用的用户id
    nickName: 新的昵称
返回：
    无
 """
def updateNickName(request):
    if ('userID' not in request.POST) or ('nickName' not in request.POST):
        return HttpResponse("参数不足")
    user_id = request.POST['userID']
    nick_name = request.POST['nickName']
    user = models.Users.objects.get(userID=user_id)
    if not user:
        return HttpResponse("没有该用户")

    user.nickName = nick_name
    user.save()
    return HttpResponse("成功")


""" 
功能：
    修改密码
参数：request包含几个POST字段
    userID: 登录用的用户id
    password: 新密码
返回：
    无
 """
def updatePassword(requset):
    if ('userID' not in requset.POST) or ('password' not in requset.POST):
        return HttpResponse("参数不足")
    user_id = requset.POST['userID']
    new_password = requset.POST['password']

    user = models.Users.objects.get(userID=user_id)
    if not user:
        return HttpResponse("没有该用户")

    user.password = new_password
    user.save()
    return HttpResponse('成功')

""" 
功能：
    查询(获得)用户昵称
参数：request包含几个POST字段
    userID: 如名
返回：
    用户名
 """
def queryNickName(request):
    if 'userID' not in request.POST:
        return HttpResponse("没有userID")
    user_id = request.POST['userID']
    user = models.Users.objects.get(userID=user_id)
    if not user:
        return HttpResponse("没有此用户")
    nick_name = user.nickName
    data = {}
    data['nickName'] = nick_name
    return HttpResponse(json.dumps(data))

""" 
功能：
    安卓端登录
参数：request包含几个POST字段
    userID: 登录用的用户id
    password: 登录密码
返回：
    登录成功返回用户昵称nickName
"""

def androidLogin(request):
    if ('userID' not in request.POST) or ('password' not in request.POST):
        return HttpResponse("参数不足")
    user_id = request.POST['userID']
    password = request.POST['password']
    user_list = models.Users.objects.filter(userID=user_id)
    if not user_list:
        return HttpResponse(0)
    if password == user_list[0].password:
        data = {}
        data['nickName'] = user_list[0].nickName
        return HttpResponse(json.dumps(data))
    return HttpResponse(0)
""" 
功能：
    删除事件
参数：request包含几个POST字段
    userID: 登录用的用户id
    eventID: 要删除的事件id
返回：
    无
"""
def deleteEvent(request):
    if ('userID' not in request.POST) or ('eventID' not in request.POST):
        return HttpResponse("参数不足")
    event_id = request.POST['eventID']
    user_id = request.POST['userID']
    event = models.Events.objects.get(Q(userID__userID=user_id)&Q(id=event_id))
    relate_item_list = models.EventsRelate.objects.filter(fatherEventID=event)
    # 删除小事件
    if relate_item_list:
        for relate_item in relate_item_list:
            relate_item.childEventID.delete()
            relate_item.fatherEventID.delete()
            relate_item.delete()
    event.delete()
    return HttpResponse()

""" 
功能：
    改变事件状态
参数：request包含几个POST字段
    userID: 登录用的用户id
    eventID: 要删除的事件id
返回：
    无
"""
def updateEventStatus(request):
    if ('unIndex' not in request.POST) or ('index' not in request.POST):
        return HttpResponse("参数不足")
    unfinished_index = request.POST['unIndex'] #未完成的下标
    index = request.POST['index'] #已完成的下标
    if unfinished_index:
        unfinished_index = unfinished_index.split(',')
        for event_id in unfinished_index:
            event = models.Events.objects.get(id=event_id)
            event.eventStatus = True
            event.save()
    if index:
        index = index.split(',')
        for event_id in index:
            event = models.Events.objects.get(id=event_id)
            event.eventStatus = False
            event.save()
    return HttpResponse()

""" 
功能：
    根据事件状态查询事件
参数：request包含几个POST字段
    userID: 登录用的id
    eventID: 要删除的事件id
返回：
    完成事件和未完成事件的列表
"""
def queryEventsByStatus(request):
    if ('userID' not in request.POST):
        return HttpResponse("参数不足")
    user_id = request.POST['userID']
    user = models.Users.objects.get(userID=user_id)
    date = datetime.datetime.now().strftime('%Y-%m-%d')
    # 获取大事件列表
    father_event_list = models.Events.objects.filter(
        Q(eventStartDate__lte=date) & Q(eventEndDate__gte=date) & Q(isSubEvent=False) & Q(userID=user))
    unfinished_event_list = []
    finished_event_list = []
    for event in father_event_list:
        if event.eventStatus:
            finished_event_list.append(
                {'id':event.id, 'title':event.eventName,
                'endDate':event.eventEndDate.strftime('%Y-%m-%d'), 
                'endTime':event.eventEndTime.strftime('%H:%M'), 
                'completed':event.eventStatus,
                'level':event.eventLevel
                }
            )
        else:
            unfinished_event_list.append(
                {'id':event.id, 'title': event.eventName, 
                'endDate': event.eventEndDate.strftime('%Y-%m-%d'), 
                'endTime': event.eventEndTime.strftime('%H:%M'), 
                'completed': event.eventStatus,
                'level':event.eventLevel
                }
            )
    data={}
    data['data'] = {'unfinished_event_list':unfinished_event_list, 
                    'finished_event_list':finished_event_list
                   }
    return HttpResponse(json.dumps(data))

""" 
功能：
    根据日期查询事件
参数：request包含几个POST字段
    userID: 登录用的id
    date: 要查询的日期
返回：
    完成事件和未完成事件的列表
"""
def queryEventByDate(request):
    if ('userID' not in request.POST) or ('date' not in request.POST):
        return HttpResponse("参数不足")
    date = request.POST['date']
    user_id = request.POST['userID']
    user = models.Users.objects.get(userID=user_id)
    event_list = models.Events.objects.filter( Q(eventStartDate__lte=date) & Q(eventEndDate__gte=date) & Q(isSubEvent=False) & Q(userID=user))
    unfinished_event_list = []
    finished_event_list = []
    for event in event_list:
        if event.eventStatus:
            finished_event_list.append(
                {'id': event.id, 'title': event.eventName, 
                'endDate': event.eventEndDate.strftime('%Y-%m-%d'),
                'endTime': event.eventEndTime.strftime('%H:%M'), 
                'completed': event.eventStatus,
                'level':event.eventLevel
                }
            )
        else:
            unfinished_event_list.append(
                {'id': event.id, 'title': event.eventName, 
                'endDate': event.eventEndDate.strftime('%Y-%m-%d'),
                'endTime': event.eventEndTime.strftime('%H:%M'), 
                'completed': event.eventStatus,
                'level':event.eventLevel
                }
            )
    data = {}
    data['data'] = {'unfinished_event_list': unfinished_event_list, 'finished_event_list': finished_event_list}
    return HttpResponse(json.dumps(data))

""" 
功能：
    更新小事件的完成状态，这个只针对事件卡片界面
参数：request包含几个POST字段
    fatherEventID: 大事件的id
    idList: 小事件id列表
返回：
    无
"""
def updateSubEventStatus(request):
    if ('idList' not in request.POST) or ('fatherEventID' not in request.POST):
        return HttpResponse("参数不足")
    idList = request.POST['idList'].split(',')
    event_id = request.POST['fatherEventID']
    if idList!=[""]:
        for chile_event_id in idList:
            event = models.Events.objects.get(id=chile_event_id)
            event.eventFinishDate = datetime.datetime.now().strftime('%Y-%m-%d')  #事件完成日期
            event.eventStatus = True  # 更改小事件的状态
            event.save()
    father_event = models.Events.objects.get(id=event_id)
    relate_item_list = models.EventsRelate.objects.filter(Q(fatherEventID=father_event))    #获得大事件关联的所有小事件的管理
    all_finished = True
    for relate_item in relate_item_list:
        if relate_item.childEventID.eventStatus == False:
            all_finished = False
            break

    if all_finished:    # 如果全部完成，则大事件设置完成
        father_event.eventFinishDate = datetime.datetime.now().strftime('%Y-%m-%d')  #事件完成日期
        father_event.eventStatus = True
        father_event.save()
    return HttpResponse('提交成功')

""" 
功能：
    事件发送
参数：request包含几个POST字段
    userID: 登录用的id
    pre_launchID: launchid
    title: 事件题目
返回：
    事件发起项的id
"""
def insertEventsLaunch(request):
    if 'userID' not in request.POST:
        return HttpResponse("无userID")
    user_id = request.POST['userID']
    if 'pre_launchID' in request.POST:
        pre_launchID = request.POST['pre_launchID']
        launchEvent = models.EventsLaunch.objects.get(id=pre_launchID)
        title = request.POST['title']
        launchEvent.eventName = title
        launchEvent.save()

    user = models.Users.objects.get(userID=user_id)

    eLanch = models.EventsLaunch()
    eLanch.userID = user
    eLanch.eventName = '1'

    eLanch.sendDate = datetime.datetime.now().strftime('%Y-%m-%d')
    eLanch.save()
    return HttpResponse(eLanch.id)


""" 
功能：
    获得某用户某天的所有事件，大事件包括小事件
    处理重复功能
参数：request包含几个POST字段
    userID: 登录用的id
    
返回：
    当天所有未完成大事件的列表，大事件里包括小事件
"""
def queryEventsInCard(request):
    if 'userID' not in request.POST:
        return HttpResponse("无userID")
    date = datetime.datetime.now().strftime('%Y-%m-%d')
    user_id = request.POST['userID']
    user = models.Users.objects.get(userID=user_id)
    #获取大事件列表，这一段处理重复功能，若事件设置重复，每天都要把完成状态设置为false
    father_event_list = models.Events.objects.filter(Q(eventStartDate__lte=date)&Q(eventEndDate__gte=date)&Q(isSubEvent=False)&Q(userID=user))
    for father_event in father_event_list:
        if father_event.isRepeat:  #判断是否是重复事件，如果是重复事件判断完成日期和当前日期是否相等
            if father_event.eventFinishDate == None:    #大事件没有完成
                relate_item_list = models.EventsRelate.objects.filter(fatherEventID = father_event)  # 获取关联表中的小事件
                for relate_item in relate_item_list:
                    if relate_item.childEventID.isRepeat:  # 小事件重复
                        if relate_item.childEventID.eventFinishDate:
                            if relate_item.childEventID.eventFinishDate.strftime('%Y-%m-%d') != date:
                                relate_item.childEventID.eventStatus = False
                                relate_item.childEventID.save()  # 保存小事件状态
            elif father_event.eventFinishDate.strftime('%Y-%m-%d') != date:    #如果相等将事件状态置为False
                father_event.eventStatus = False
                father_event.save()
                relate_item_list = models.EventsRelate.objects.filter(fatherEventID = father_event) #获取关联表中的小事件
                for relate_item in relate_item_list:
                    if relate_item.childEventID.isRepeat:    #小事件重复
                        relate_item.childEventID.eventStatus=False
                        relate_item.childEventID.save()     #保存小事件状态

    #返回查找到的大事件
    data={}
    event_list=[]
    for event in father_event_list:
        if event.eventStatus:
            continue
        task={'id': event.id,'title': event.eventName,
            'desc': event.eventDescription, 'completed': event.eventStatus,
            'level':event.eventLevel}
        child_events=[]
        relate_item_list=models.EventsRelate.objects.filter(Q(fatherEventID=event))  #获取关联事件
        for relate_item in relate_item_list:
            child_event=relate_item.childEventID
            if not child_event.eventStatus:
                sub_event = {'id': child_event.id, 'title': child_event.eventName,
                    'endTime': child_event.eventEndTime.strftime('%H:%M'),
                    'desc':child_event.eventDescription,
		            'completed':child_event.eventStatus,
                    'level':event.eventLevel }
                child_events.append(sub_event)
        task['child_events'] = child_events
        event_list.append(task)
    data['data'] = event_list
    return HttpResponse(json.dumps(data))

""" 
功能：
    获得用户所发送事件的监控数据
参数：request包含几个POST字段
    userID: 登录用的id
返回：
    发起事件的完成比例(JSON格式)
"""
def queryEventsMonitor(request):
    if 'userID' not in request.POST:
        return HttpResponse("无userID")
    user_id = request.POST['userID']
    user = models.Users.objects.get(userID=user_id)
    # 查询 EventsLaunch表， 当前用户的所有发起事件launch_item
    launch_item = models.EventsLaunch.objects.filter(userID=user)

    obj_list = []
    for one in launch_item:   # 在 EventsReceive 表中，查询当前所有 launchID 的事件
        if one.eventName == '1':
            continue
        else:   # 不为1，取出eventName,遍历所有该launch_item对应的事件，判断是否完成，最后得出 完成事件/事件总数*100%
            obj = {}
            obj['title'] = one.eventName
            # titleList.append(one.eName)
            elist = models.EventsReceive.objects.filter(eventsLaunchID=one)
            count = len(elist)
            obj['count'] = count
            # countList.append(count)
            obj['date'] = one.sendDate.strftime('%Y-%m-%d')
            completed = 0
            for e in elist:
                if e.eventID.eventStatus:   #完成事件
                    completed+=1
                obj['date'] = e.eventID.eventEndDate.strftime('%Y-%m-%d')
            obj['completed'] = completed
            if count == 0:
                obj['progress'] = 0
            else:
                obj['progress'] = completed*100//count
            # completedList.append(completed)
            obj_list.append(obj)
    # 返回JSON, 包括题目，两种事件数量(事件比例)
    data = {}
    data['data'] = obj_list
    return  HttpResponse(json.dumps(data))

""" 
功能：
    获得事件的各个属性，在修改事件的时候需要获得保存的事件的各个属性
参数：request包含几个POST字段
    id: 事件id
返回：
    发起事件的完成比例(JSON格式)
"""
def queryEventDetail(request):
    if 'id' not in request.POST:
        return HttpResponse("无userID")
    event_id = request.POST['id']
    event = models.Events.objects.get(id=event_id)
    data = {}
    data['uID'] = event.userID.userID
    data['title'] = event.eventName
    data['beginDate'] = event.eventStartDate.strftime('%Y-%m-%d')
    data['beginTime'] = event.eventStartTime.strftime('%H:%M')
    data['endDate'] = event.eventEndDate.strftime('%Y-%m-%d')
    data['endTime'] = event.eventEndTime.strftime('%H:%M')
    data['repeat'] = event.isRepeat
    data['isSubEvent'] = event.isSubEvent
    data['desc'] = event.eventDescription
    data['level'] = event.eventLevel
    receList = models.EventsReceive.objects.filter(eventID=event)
    if receList:
        data['isReceive'] = 1
    else:
        data['isReceive'] = 0
    child_events = []
    #开始获取小事件
    relate_item_list = models.EventsRelate.objects.filter(fatherEventID=event)
    for relate_item in relate_item_list:
        sub_event = {}
        sub_event['id'] = relate_item.childEventID.id
        sub_event['uID'] = relate_item.childEventID.userID.userID
        sub_event['title'] = relate_item.childEventID.eventName
        sub_event['beginDate'] = relate_item.childEventID.eventStartDate.strftime('%Y-%m-%d')
        sub_event['beginTime'] = relate_item.childEventID.eventStartTime.strftime('%H:%M')
        sub_event['endDate'] = relate_item.childEventID.eventEndDate.strftime('%Y-%m-%d')
        sub_event['endTime'] = relate_item.childEventID.eventEndTime.strftime('%H:%M')
       
        sub_event['repeat'] = relate_item.childEventID.isRepeat
        sub_event['isSubEvent'] = relate_item.childEventID.isSubEvent
        sub_event['desc'] = relate_item.childEventID.eventDescription
        sub_event['level'] = relate_item.childEventID.eventLevel
        child_events.append(sub_event)
    data['child_events'] = child_events
    return HttpResponse(json.dumps(data))

""" 
功能：
    添加事件
参数：request.POST包含事件所有字段
    
返回：
    无
"""
def insertOrUpdateEvent(request):
    e_id = request.POST['id'] # id用来判断是修改事件还是创建新事件，若是创建新事件，id也要传，不过是NULL
    event_name = request.POST['title']
    user_id = request.POST['uID']
    user = models.Users.objects.get(userID=user_id)
    start_date = request.POST['beginDate']
    start_time = request.POST['beginTime']
    end_date = request.POST['endDate']
    end_time = request.POST['endTime']
    is_repeat = request.POST['repeat']
    isSubEvent = request.POST['isSubEvent']
    event_level = request.POST['level']
    desc = request.POST['desc']
    todos = request.POST['todos'] #小任务
    todos = todos.replace('true', 'True')
    todos = todos.replace('false', 'False')
    todos = eval(todos)   #字符串转字典
    if e_id != '':  # 如果存在修改的id的就对已有的数据进行修改
        event_object = models.Events.objects.get(id=e_id) # 修改事件
    else:
        #保存大任务对象
        event_object = models.Events()    # 新建事件
    event_object.userID = user
    event_object.eventName = event_name
    event_object.eventStartDate = start_date
    event_object.eventStartTime = start_time
    event_object.eventEndDate = end_date
    event_object.eventEndTime = end_time
    event_object.eventLevel = event_level
   
    if is_repeat == 'false':
        is_repeat = False
    elif is_repeat == 'true':
        is_repeat = True
    else:
        is_repeat = False
    event_object.isRepeat = is_repeat
    event_object.eventStatus = False
    if isSubEvent == 'false':
        isSubEvent = False
    elif isSubEvent == 'true':
        isSubEvent = True
    else:
        isSubEvent = False
    event_object.isSubEvent = isSubEvent
    event_object.eventDescription = desc
    event_object.save()
    #保存小事件对象
    for subtodo in todos:   #保存小事件
        if 'id' in subtodo and subtodo['id'] != '':  # 如果存在修改的id的就对已有的数据进行修改
            sub_event = models.Events.objects.get(id=subtodo['id'])
        else:
            sub_event = models.Events()
        sub_event.userID=user
        sub_event.eventName = subtodo['title']
        sub_event.eventStartDate = subtodo['beginDate']
        sub_event.eventStartTime=subtodo['beginTime']
        sub_event.eventEndDate = subtodo['endDate']
        sub_event.eventEndTime = subtodo['endTime']
        sub_event.isRepeat = subtodo['repeat']
        sub_event.eventLevel = subtodo['level']
        sub_event.eventStatus = False
        sub_event.isSubEvent = True
        sub_event.eventDescription = subtodo['desc']
        sub_event.save()
        #事件关联表
        if 'id' in subtodo:
            if subtodo['id'] == '':
                econtactObj = models.EventsRelate()
                econtactObj.fatherEventID = event_object
                econtactObj.childEventID = sub_event
                econtactObj.save()
        else:
            econtactObj = models.EventsRelate()
            econtactObj.fatherEventID = event_object
            econtactObj.childEventID = sub_event
            econtactObj.save()

    # 判断这个事件是否是别人发送的事件
    if 'launchID' in request.POST:
        launchID = request.POST["launchID"]
        launch_object = models.EventsLaunch.objects.get(id=launchID)
        receive_item = models.EventsReceive()
        receive_item.eventsLaunchID = launch_object
        receive_item.eventID = event_object
        receive_item.receiveDate = datetime.datetime.now().strftime('%Y-%m-%d')
        receive_item.save()
    return HttpResponse('保存成功')

""" 
功能：
    上传建议
参数：
    userID
    suggestion
返回：
    无
"""
def insertSuggestion(request):
    print(request.POST)
    if('userID' not in request.POST) or ('suggestion' not in request.POST):
        return HttpResponse("参数不足")
    user_id = request.POST['userID']
    suggestion_text = request.POST['suggestion']
    user_sug = models.UserSuggestions()
    user_sug.userID = models.Users.objects.get(userID=user_id)
    user_sug.suggestionText = suggestion_text
    user_sug.save()
    return HttpResponse("成功")
    









